package com.taotao.manage.controller;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.manage.pojo.ContentCategory;
import com.taotao.manage.service.ContentCategoryService;

@Controller
@RequestMapping("content/category")
public class ContentCategoryController {
	
	@Autowired 
	private ContentCategoryService contentCategoryService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ResponseEntity<List<ContentCategory>> queryContentCategoryListByParentId(
			@RequestParam(value= "id",defaultValue = "0")Long id){
		try {
			ContentCategory contentCategory = new ContentCategory();
			contentCategory.setParentId(id);
			List<ContentCategory> list = contentCategoryService.queryListByWhere(contentCategory);
			if (CollectionUtils.isEmpty(list)) {
				return ResponseEntity.notFound().build();
			}
			return ResponseEntity.ok(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<ContentCategory> saveContentCategory(ContentCategory contentCategory){
		try {
			contentCategoryService.saveContentCategoryAndParent(contentCategory);
			return ResponseEntity.status(HttpStatus.CREATED).body(contentCategory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
		
	}
	
	@RequestMapping(method = RequestMethod.PUT)
	public ResponseEntity<Void> updateContentCategory(ContentCategory contentCategory){
		try {
			Integer count = contentCategoryService.updateSelective(contentCategory);
			if (count > 0) {
				return ResponseEntity.noContent().build();
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	

	@RequestMapping(method = RequestMethod.DELETE)
	public ResponseEntity<Void> deleteContentCategory(@RequestParam("parentId")Long parentId,@RequestParam("id")Long id){
		try {
			contentCategoryService.deleteContentCategory(parentId,id);
				return ResponseEntity.noContent().build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	

}
